import React, { useEffect } from 'react';
import { Modal, Form, Input, Select, Radio, DatePicker, Upload, Avatar, message } from 'antd';
import { PlusOutlined, UserOutlined } from '@ant-design/icons';
import { createUser, updateUser, checkUsernameAvailable, checkEmailAvailable } from '@/services/userManagementApi';
import { uploadFile } from '@/services/systemManagementApi';
import moment from 'moment';

interface UserFormProps {
  visible: boolean;
  mode: 'create' | 'edit';
  initialValues?: USER.UserModel;
  onCancel: () => void;
  onSuccess: () => void;
}

const UserForm: React.FC<UserFormProps> = ({
  visible,
  mode,
  initialValues,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = React.useState(false);
  const [avatarUrl, setAvatarUrl] = React.useState<string>('');

  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && initialValues) {
        form.setFieldsValue({
          ...initialValues,
          birth_date: initialValues.birth_date ? moment(initialValues.birth_date) : undefined,
        });
        setAvatarUrl(initialValues.avatar || '');
      } else {
        form.resetFields();
        setAvatarUrl('');
      }
    }
  }, [visible, mode, initialValues, form]);

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData = {
        ...values,
        birth_date: values.birth_date ? values.birth_date.format('YYYY-MM-DD') : undefined,
        avatar: avatarUrl,
      };

      if (mode === 'create') {
        await createUser(submitData);
        message.success('用户创建成功');
      } else {
        await updateUser(initialValues!.id, submitData);
        message.success('用户更新成功');
      }

      onSuccess();
    } catch (error) {
      message.error(mode === 'create' ? '用户创建失败' : '用户更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 检查用户名是否可用
  const checkUsername = async (rule: any, value: string) => {
    if (!value) return;
    if (mode === 'edit' && value === initialValues?.username) return;
    
    try {
      const response = await checkUsernameAvailable(value);
      if (!response.data.available) {
        throw new Error('用户名已存在');
      }
    } catch (error) {
      throw new Error('用户名已存在');
    }
  };

  // 检查邮箱是否可用
  const checkEmail = async (rule: any, value: string) => {
    if (!value) return;
    if (mode === 'edit' && value === initialValues?.email) return;
    
    try {
      const response = await checkEmailAvailable(value);
      if (!response.data.available) {
        throw new Error('邮箱已存在');
      }
    } catch (error) {
      throw new Error('邮箱已存在');
    }
  };

  // 处理头像上传
  const handleAvatarUpload = async (file: File) => {
    try {
      const response = await uploadFile({
        file,
        usage_type: 'avatar',
      });
      setAvatarUrl(response.data.file_url);
      message.success('头像上传成功');
      return false; // 阻止默认上传行为
    } catch (error) {
      message.error('头像上传失败');
      return false;
    }
  };

  // 上传按钮
  const uploadButton = (
    <div>
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>上传头像</div>
    </div>
  );

  return (
    <Modal
      title={mode === 'create' ? '新建用户' : '编辑用户'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={600}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          role: 'user',
          status: 'active',
          gender: 'other',
        }}
      >
        <Form.Item label="头像">
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <Avatar
              size={80}
              src={avatarUrl}
              icon={<UserOutlined />}
            />
            <Upload
              showUploadList={false}
              beforeUpload={handleAvatarUpload}
              accept="image/*"
            >
              {uploadButton}
            </Upload>
          </div>
        </Form.Item>

        <Form.Item
          name="username"
          label="用户名"
          rules={[
            { required: true, message: '请输入用户名' },
            { min: 3, max: 20, message: '用户名长度为3-20个字符' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线' },
            { validator: checkUsername },
          ]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>

        {mode === 'create' && (
          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, max: 20, message: '密码长度为6-20个字符' },
            ]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
        )}

        <Form.Item
          name="nickname"
          label="昵称"
          rules={[
            { required: true, message: '请输入昵称' },
            { max: 50, message: '昵称不能超过50个字符' },
          ]}
        >
          <Input placeholder="请输入昵称" />
        </Form.Item>

        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入有效的邮箱地址' },
            { validator: checkEmail },
          ]}
        >
          <Input placeholder="请输入邮箱" />
        </Form.Item>

        <Form.Item
          name="phone"
          label="手机号"
          rules={[
            { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
          ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item
          name="gender"
          label="性别"
        >
          <Radio.Group>
            <Radio value="male">男</Radio>
            <Radio value="female">女</Radio>
            <Radio value="other">其他</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name="birth_date"
          label="出生日期"
        >
          <DatePicker
            style={{ width: '100%' }}
            placeholder="请选择出生日期"
            disabledDate={(current) => current && current > moment().endOf('day')}
          />
        </Form.Item>

        <Form.Item
          name="role"
          label="角色"
          rules={[{ required: true, message: '请选择角色' }]}
        >
          <Select placeholder="请选择角色">
            <Select.Option value="user">用户</Select.Option>
            <Select.Option value="admin">管理员</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            <Select.Option value="active">正常</Select.Option>
            <Select.Option value="inactive">未激活</Select.Option>
            <Select.Option value="banned">已封禁</Select.Option>
          </Select>
        </Form.Item>

        {mode === 'edit' && (
          <>
            <Form.Item
              name="level"
              label="等级"
              rules={[
                { type: 'number', min: 1, max: 100, message: '等级范围为1-100' },
              ]}
            >
              <Input type="number" placeholder="请输入等级" />
            </Form.Item>

            <Form.Item
              name="experience"
              label="经验值"
              rules={[
                { type: 'number', min: 0, message: '经验值不能为负数' },
              ]}
            >
              <Input type="number" placeholder="请输入经验值" />
            </Form.Item>

            <Form.Item
              name="points"
              label="积分"
              rules={[
                { type: 'number', min: 0, message: '积分不能为负数' },
              ]}
            >
              <Input type="number" placeholder="请输入积分" />
            </Form.Item>
          </>
        )}
      </Form>
    </Modal>
  );
};

export default UserForm;
